package com.example.rwq_test.designParttern.multiThread.TwoPhaseTermination.cyclicBarrierCountDownLanch;

import java.util.concurrent.*;

/**
 * TODO note
 *
 * @author renweiqiang
 * @version 1.0.0
 * @createTime 2022/11/19
 */
public class Main {
    private static final int THREADS = 3;

    public static void main(String[] args) {
        System.out.println("BEGIN");

        //由ExecutorService提供进行工作的线程
        ThreadPoolExecutor service = new ThreadPoolExecutor(THREADS, THREADS, 0L, TimeUnit.MILLISECONDS,
                new LinkedBlockingDeque<>(314159),
                new ThreadPoolExecutor.AbortPolicy());


        //屏蔽解除时的操作
        Runnable barrierAction = new Runnable() {
            @Override
            public void run() {
                System.out.println("Barrier Action!");
            }
        };

        //用于使线程步调一致
        //CyclicBarrier cyclicBarrier = new CyclicBarrier(THREADS);
        CyclicBarrier cyclicBarrier = new CyclicBarrier(THREADS, barrierAction);

        //用于确认是否结束
        CountDownLatch downLatch = new CountDownLatch(THREADS);

        try {
            //开始工作
            for (int i = 0; i < THREADS; i++) {
                service.execute(new MyTask(cyclicBarrier, downLatch, i));
            }
            System.out.println("AWAIT");
            downLatch.await();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            service.shutdown();
            System.out.println("END");
        }
    }
}
